package us.congcong.rsshunter.service;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import us.congcong.rsshunter.config.LocalConstant;
import us.congcong.rsshunter.model.SampleChannel;
import us.congcong.rsshunter.model.SampleContent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GiteeRssService {
	public static void main(String[] args) {
		GiteeRssService wr = new GiteeRssService();
		wr.produceRss();
	}

	private static String baseUrl = "https://gitee.com";

	public Map<String, Object> produceRss() {
		Map<String, Object> info = new HashMap<String,Object>();
		
		SampleChannel channel = new SampleChannel();
		List<SampleContent> list = new ArrayList<SampleContent>();
		
		Document doc = null;
		try {
			doc = Jsoup.connect(baseUrl + "/explore/recommend").get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(doc != null){
			channel.setTitle("Gitee for recommend");
			channel.setDescription(LocalConstant.authorInfo);
			channel.setLink(baseUrl);
			
			Elements items = doc.getElementById("git-discover-list").children();

			for (Element item : items) {
				Element titleE = item.select("div.project-title").first();
				String title = titleE.select("a").first().text();
				String url = titleE.select("a").first().attr("href");

				//Content
				String desc = item.select("div.project-desc").first().text();

				SampleContent content = new SampleContent();
				try {
					String text = Jsoup.connect(baseUrl + url).get().html();
					//here shoud be html
					content.setSummary(text);
				}catch (IOException e) {
					e.printStackTrace();
				}
				content.setTitle(title + desc);
				content.setCreatedDate(new Date());
				content.setUrl(url);
				
				list.add(content);
			}
		} else {
			return null;
		}
		info.put("channel", channel);
		info.put("items", list);
		return info;
	}

}
